package com.wanqing.utils;


import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.wanqing.constant.MessageConstant;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Component
@ConfigurationProperties(prefix = "wanqing.oss")
@Data
@Slf4j
public class QiniuOssUtill {
    private String accessKey;
    private String secretKey;
    private String bucket;
    private String url;

    public String upload(MultipartFile file) throws IOException {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region1());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
        //生成上传凭证，然后准备上传
        String accessKey = this.accessKey;
        String secretKey = this.secretKey;
        String bucket = this.bucket;
        //生成一个唯一的文件名，以避免文件上传时出现名称冲突
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty()) {
            return MessageConstant.UPLOAD_FAILED;
        }
        String fileKey = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        // 上传文件
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        Response response = uploadManager.put(file.getInputStream(), fileKey, upToken, null, null);
        log.info("上传文件成功，文件地址为：{}", url + fileKey);
        // 返回文件url
        return url + fileKey;
    }
}
